package com.yishusmt.wechatapi.wechatdev.serviceImpl;

import com.yishusmt.wechatapi.wechatdev.constant.ItemConstant;
import com.yishusmt.wechatapi.wechatdev.dto.base.Item;
import com.yishusmt.wechatapi.wechatdev.entity.ItemEntity;
import com.yishusmt.wechatapi.wechatdev.entity.TextMessageEntity;
import com.yishusmt.wechatapi.wechatdev.mapper.ItemEntityMapper;
import com.yishusmt.wechatapi.wechatdev.mapper.TextMessageEntityMapper;
import com.yishusmt.wechatapi.wechatdev.service.ArticleService;
import com.yishusmt.wechatapi.wechatdev.utils.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;


/**
 * 文章消息处理
 *
 * @author zhangyi
 * @date 2018/8/31 13:41
 */
@Service
@CacheConfig(cacheNames = "articles")
public class AricleServiceImpl  implements ArticleService {

    @Autowired
    private ItemEntityMapper itemEntityMapper;

    @Autowired
    private TextMessageEntityMapper textMessageEntityMapper;

    @Cacheable(key = "#id")
    @Override
    public Object welArticle(Long id) {
        //关注后的文章详情
        Item itemObject = new Item();
        Optional<ItemEntity> itemEntity = Optional.ofNullable(itemEntityMapper.selectByPrimaryKey(id));
        TextMessageEntity textMessageEntity = null;
        boolean present = itemEntity.isPresent();
        if(!present){
            textMessageEntity = textMessageEntityMapper.selectByPrimaryKey(id);
        }else{
            ItemEntity item = itemEntity.get();
            itemObject.setTitle(item.getTitle());
            itemObject.setDescription(item.getDescription());
            itemObject.setPicUrl(item.getPicUrl());
            itemObject.setUrl(item.getUrl());
        }
        return itemEntity.isPresent()?itemObject: textMessageEntity.getTextDesc();
    }

    /**
     * 清除缓存文章
     *
     * @param itemEntity
     * @return
     */
    @CacheEvict(key = "#itemEntity.id")
    @Override
    public int updateArticle(ItemEntity itemEntity) {
        return itemEntityMapper.updateByPrimaryKey(itemEntity);
    }


    /**
     * 清除纯文本缓存文章
     *
     * @param textMessageEntity
     * @return
     */
    @CacheEvict(key = "#textMessageEntity.id")
    @Override
    public int updateText(TextMessageEntity textMessageEntity) {
        return textMessageEntityMapper.updateByPrimaryKey(textMessageEntity);
    }
}
